<?php


namespace App\Services;


use App\Models\Article;
use App\Utils\Code;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use \Illuminate\Database\Eloquent\Builder;

class ArticleService extends BaseService
{
    /**
     * 创建数据
     * @param array $params
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     * @throws \Exception
     */
    public function store(array $params) {
        if (!$this->checkParams($params)){
            throw new \Exception('请求参数验证不通过', Code::PARAMETER_ERROR);
        }
        return DB::transaction(function () use ($params){
            $model = new Article();
            if (Article::where('name', $params['name'])->first()) {
                throw new \Exception('名称已经存在', Code::EXIST_REPEAT);
            }
            $model->name = $params['name'];
            if (isset($params['path']) && $params['path']){
                $model->path = $params['path'];
            }
            if (isset($params['remarks']) && $params['remarks']){
                $model->remarks = $params['remarks'];
            }
            if (isset($params['sort']) && is_numeric($params['sort'])){
                $model->sort = (int)$params['sort'];
            }
            return $model->save();
        });
    }

    /**
     * 数据信息
     * @param $id
     * @param bool $simple
     * @param bool $abnormal
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     * @throws \Exception
     */
    public function show($id, $abnormal = true) {
        $model = Article::where('id', $id)->first();
        if (!$model && $abnormal){
            throw new \Exception('不存在的ID', Code::EMPTY_DATA);
        }
        return $model;
    }

    /**
     * 更新数据
     * @param $id
     * @param array $params
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     * @throws \Exception
     */
    public function update($id, array $params) {
        if (!$this->checkParams($params, true)){
            throw new \Exception('请求参数验证不通过', Code::PARAMETER_ERROR);
        }
        return DB::transaction(function () use ($id, $params){
            $model = $this->show($id);
            if (Article::where('name', $params['name'])->where('id', '<>', $id)->first()) {
                throw new \Exception('名称已经存在', Code::EXIST_REPEAT);
            }
            $model->name = $params['name'];
            if (isset($params['path']) && $params['path']){
                $model->path = $params['path'];
            }
            if (isset($params['remarks']) && $params['remarks']){
                $model->remarks = $params['remarks'];
            }
            if (isset($params['sort']) && is_numeric($params['sort'])){
                $model->sort = (int)$params['sort'];
            }
            $model->save();
            return $this->show($id);
        });
    }

    /**
     * 删除数据
     * @param $id
     * @return mixed
     * @throws \Exception
     */
    public function destroy(array $ids = []) {
        if (!$this::$admin) {
            throw new \Exception('你没有权限进行删除', Code::LACK_OF_CONDITIONS);
        }
        return DB::transaction(function () use ($ids) {
            return Article::whereIn('id', $ids)->delete();
        });
    }

    /**
     * 数据分页
     * @param array $params
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function lists(array $params = []) {
        if (isset($params['mode']) && $params['mode'] == 'select') {
            $model = Article::select(['id', 'sort', 'name']);
        } else {
            $model = new Article();
        }
        if (isset($params['name']) && $params['name']) {
            $model = $model->where('name', 'like', '%'.$params['name'].'%');
        }
        $lists = $model->orderBy('sort', 'asc')->get();
        return $lists;
    }

    /**
     * 验证参数
     * @param array $params
     * @param bool $isUpdate
     * @return array
     * @throws \Exception
     */
    private function checkParams(array $params, $isUpdate = false){
        $rules = [
            'name' => ['bail', 'required', 'string', 'between:1,50'],
            'sort' => ['bail', 'nullable', 'integer'],
        ];
        if ($isUpdate){
            // 删除必选条件
            foreach ($rules as $field => &$rule){
                if (isset($rule[1]) && $rule[1] == 'required') {
                    unset($rule[1]);
                }
            }
        }
        $validator = Validator::make($params, $rules, [], [
            'name' => '名称',
            'sort' => '排序字段'
        ]);
        if ($validator->fails()) {
            throw new \Exception($validator->errors()->first(), Code::PARAMETER_ERROR);
        }
        return $params;
    }
}
